<template>
  <div id="order">
    <van-nav-bar
      title="填写订单"
      left-arrow
      :fixed=true
      @click-left="handleToBack"
    />
    <!-- 选择收货地址 -->
    <van-contact-card
      :type="address_type"
      add-text="选择收货地址"
      :name="address_name"
      :tel="address_phone"
      @click="chooseAddress"
      style="margin-top: 52px"
    />
    <van-cell-group>
      <van-cell
        title="送达时间"
        :value="deliveryTime"
        is-link
        @click="showTimePickView"
      >
        <template #label>
          <span class="custom-title">超过十分钟可获得积分补偿</span>
          <van-icon name="question-o" />
        </template>
      </van-cell>
      <!-- 送货时间区间选择器 -->
      <TimeIntervalList
        ref="timeInterval"
        :showDateTimePopView="showDateTimePopView"
        @changeData="changeData(arguments)">
      </TimeIntervalList>
      <!-- 商品缩略图 -->
      <div class="wrapper" @click="goToGoodsList">
        <scroll
          class="productImageWrapper"
          ref="productImageWrapper"
          :probeType="3"
          :listenScroll="true"
          :scrollX="true"
          :data="goods"
        >
          <ul class="imageWrapper" ref="imageWrapper">
            <li
              ref="subWrapper"
              style="display:inline"
              v-for="(item,index) in goods"
              :key="index"
            >
              <img :src="item.smallImage" alt="">
            </li>
          </ul>
        </scroll>
        <ul class="productCount">
          <span>{{selectedCount}}</span>
          <van-icon name="arrow" />
        </ul>
      </div>
    </van-cell-group>
    <!-- 支付方式选择 -->
    <pay-type />

    <!-- 优惠券及积分满减 -->
    <van-cell-group style="margin-top: 10px">
      <van-coupon-cell :coupons="coupons"
                       :chosen-coupon="chosenCoupon"
                       @click="showList = true" />
      <van-cell>
        <!-- 优惠券列表 -->
        <van-popup v-model="showList"
                   position="bottom">
          <van-coupon-list :coupons="coupons"
                           :chosen-coupon="chosenCoupon"
                           @change="onChange"
                           @exchange="onExchange" />
        </van-popup>
        <span slot="title">使用{{integral}}微信支付￥<b>{{integralToprice}}</b></span>
        <van-switch v-model="checked"
                    slot="right-icon"
                    @input="onInput"
                    active-color="#07c160" />
      </van-cell>
    </van-cell-group>
    <!-- 备注 -->
    <van-cell-group style="margin-top: 10px">
      <van-field label="备注"
                 type="textarea"
                 placeholder="选填,可以告诉我们您的特殊需求"
                 rows="1"
                 autosize
                 is-link />
    </van-cell-group>

    <!-- 商品金额 -->
    <van-cell-group style="margin-top: 10px">
      <van-cell title="商品金额">
        <div class="money">{{(selectedTotalPrice/100)}}</div>
      </van-cell>
      <van-cell title="配送费">
        <div class="money">0.00</div>
      </van-cell>
      <van-cell title="积分"
                v-show="isShowPreferential">
        <div class="integralToMoney">-{{integralToprice}}</div>
      </van-cell>
    </van-cell-group>

    <!-- 提交订单 -->
    <van-submit-bar :price="actualPrice"
                    label="实付"
                    button-text="提交订单"
                    @submit="onSubmit" />
    <!-- 路由出口 -->
    <transition name="router-slider" mode="out-in">
      <router-view />
    </transition>
  </div>
</template>

<script>
// import Scroll from '@/components/common/scroll/Scroll'
import PayType from '@/components/common/paytype/PayType'
import { mapGetters, mapMutations } from 'vuex'
import { getLocalStore } from '@/config/global'
// 引入发布订阅
import { CHOOSE_USER_ADDRESS } from '@/config/pubsub-type'
import PubSub from 'pubsub-js'

// 送货时间区间组件
import TimeIntervalList from './childComps/TimeInterValList'

export default {
  name: 'Order',
  mounted () {
    console.log(Function.prototype.before)
  },
  data () {
    return {
      address_type: 'add',           //地址卡片类型
      address_name: null,            // 收货人
      address_phone: null,           // 收货人电话
      address_id: null,              // 收货人地址ID

      radio: '1',                    // 支付方式
      checked: false,                // 积分兑换开关
      isShowPreferential: false,     // 展示积分兑换
      integral: 800,                // 积分,
      showList: false,              // 展示优惠列表

      deliveryTime: '请选择送达时间',
      showDateTimePopView: false,
      coupons: [
        {                  // 优惠券信息
        available: 1,
        condition: '无使用门槛\n最多优惠1.5元',
        reason: '',
        value: 150,
        name: '优惠券',
        startAt: 1549104000,
        endAt: 1614592000,
        valueDesc: '1.5',
        unitDesc: '元'
        },
        {                  // 优惠券信息
        available: 1,
        condition: '无使用门槛\n最多优惠2元',
        reason: '',
        value: 200,
        name: '优惠券',
        startAt: 1549104000,
        endAt: 1614592000,
        valueDesc: '2',
        unitDesc: '元'
      }],
      chosenCoupon: -1,
    };
  },
  computed: {
    // 数量
    ...mapGetters({
      selectedCount: 'SELECTED_GOODS_COUNT',
      goods: 'SELECTED_GOODS',
      selectedTotalPrice: 'SELECTED_GOODS_PRICE',
      shopCart: 'shopCart'
    }),
    // 实际价格
    actualPrice () {
      // 如果用户使用积分兑换或使用优惠券
      let finalPrice
      if (this.checked) {
        let discountsPrice = this.integralToprice.toFixed(2).toString().replace('.', '')
        finalPrice = this.selectedTotalPrice - discountsPrice
      } else {
        finalPrice = this.selectedTotalPrice
      }
      // 是否选择优惠券
      if (this.chosenCoupon > -1) {
        return finalPrice - this.coupons[this.chosenCoupon].value
      } else {
        return finalPrice
      }
    },
    // 计算积分兑换人民币
    integralToprice () {
      return this.integral > 0  ? this.integral / 100 : ''
    }
  },
  mounted () {
    // 初始化本地购物车数据
    this.INIT_SHOP_CART()
    // 有商品才加载可滑动组件
    if (this.goods.length > 0) {
      this.$nextTick(() => {
        this._initScroll()
      })
    }
    // 订阅发布的通知
    PubSub.subscribe(CHOOSE_USER_ADDRESS, (msg, data) => {
      if (msg == CHOOSE_USER_ADDRESS) {
        // 修改卡片类型
        this.address_type = 'edit'
        this.address_name = data.name
        this.address_phone = data.tel
        this.address_id = data.id
      }
    })
  },
  components: {
    TimeIntervalList,
    // Scroll,
    PayType
  },
  methods: {
    // 初始化本地购物车数据
    ...mapMutations(['INIT_SHOP_CART']),
    // 1.初始化滚动视图
    _initScroll () {
      if (this.goods) {
        this.$refs.imageWrapper.style.width = (this.$refs.subWrapper.length * 60) + 'px';
      }

    },
    // 2.返回到上个界面
    handleToBack () {
      this.$router.back()
    },
    // 3.提交订单
    onSubmit () {
      if (!this.address_name) {
        this.$toast({
          message: '请选择收货地址',
          duration: 800
        })
      } else if (this.deliveryTime == '请选择送达时间') {
        ({
          message: this.deliveryTime,
          duration: 800
        })
      } else {
        this.$toast({
          message: '提交订单',
          duration: 800
        })
      }
    },
    // 4.switch开关
    onInput (checked) {
      let discountsPrice = this.integralToprice * 100
      // 4.1 判断积分使用条件是否满足
      if (discountsPrice > this.selectedTotalPrice) {
        // 4.2不能使用积分
        this.$dialog.alert({
          message: '您的实际价格小于积分兑换价格,建议您在多买几件'
        }).then(() => {
          this.checked = false
        })
      } else {
        this.isShowPreferential = !this.isShowPreferential
      }
    },
    goToGoodsList () {
      this.$router.push({ name: 'OrderGoodsList' })
    },
    // 选择地址
    chooseAddress () {
      this.$router.push('/order/myAddress')
    },
    // 选择优惠券
    onChange (index) {
      this.showList = false
      this.chosenCoupon = index
    },
    // 优惠券兑换
    onExchange (code) {
      this.coupons.push(coupon)
    },
    // 显示时间选择器
    showTimePickView () {
      this.showDateTimePopView = true
    },
    changeData () {
      this.showDateTimePopView = arguments[0][0]
      this.deliveryTime = arguments[0][1]
    }
  },
  beforeDestroy () {
    // 销毁订阅
    PubSub.unsubscribe(CHOOSE_USER_ADDRESS)
  }
}
</script>
<style lang="scss" scoped>
#order {
  @include setWH(100%, 100%);
  background-color: $bg-color-page;
  margin-bottom: px2rem(88);
  .wrapper {
    @include setWH(100%, px2rem(70));
    position: relative;
    .productImageWrapper {
      @include flexType(flex-start);
      flex-flow: row nowrap;
      white-space: nowrap;
      @include setWH(80%, px2rem(70));
      overflow: hidden;
      .imageWrapper {
        flex-wrap: nowrap;
        img {
          @include setWH(px2rem(52), px2rem(52));
        }
      }
    }
    .productCount {
      position: absolute;
      right: px2rem(2);
      top: px2rem(26);
      color: $text-color-pl;
    }
  }
  .pay-type {
    img {
      @include setWH(px2rem(30), px2rem(25));
      vertical-align: middle;
      padding-right: px2rem(5);
    }
  }

  /*转场动画*/
  .router-slider-enter-active,
  .router-slider-leave-active {
    transition: all .3s;
  }
  .router-slider-enter,
  .router-slider-leave-active {
    transform: translate3d(px2rem(35), 0, 0);
    opacity: 0;
  }
}
</style>

